package com.javajun.endofterm.service;

import com.javajun.endofterm.common.CommonService;
import com.javajun.endofterm.entity.SysRole;
import com.javajun.endofterm.entity.SysUser;
import com.javajun.endofterm.repository.SysUserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * Author: Xiong Limin
 * Date: 2020-12-05-6:41 下午
 */
@Service
public class SysUserService extends CommonService<SysUser, Integer> implements UserDetailsService {
    @Autowired
    private SysUserRepository sysUserRepository;

    public SysUser findByUsername(String username) {
        return  sysUserRepository.findByUsername(username);
    }

    public SysUser getLoadSysUser() {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        String username = auth.getName();
        return sysUserRepository.findByUsername(username);
    }

    public boolean whetherStudent() {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        Set<String> rolSet = AuthorityUtils.authorityListToSet(auth.getAuthorities());
        return rolSet.contains("ROLSE_STUDENT");
    }


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 根据用户名查找用户
        SysUser user = sysUserRepository.findByUsername(username);

        // 如果用户不存在，则抛出异常
        if (user == null) {
            throw new UsernameNotFoundException("用户" + username + " 不存在");
        }
        // 获取用户角色
        List<SysRole> roles = user.getSysRoleList();
        List<GrantedAuthority> authorities = new ArrayList<>();
        for (SysRole role : roles) {
            authorities.add(new SimpleGrantedAuthority(role.getCode()));
        }

        return new User(user.getUsername(), user.getPassword(), authorities);
        // return new MyUser(user.getUsername(), user.getPassword(), user.getName(), authorities);
    }
}
